<?php
require_once("authenticate.php");
require_once("DatabaseConnect.php");
require_once("SMA.php");
require_once("EMA.php");
require_once("PeclStrats.php");

//stoping the page from timeing out
set_time_limit(130);
//Database connection
$con = Remoteconnect();
if ($con == null) {
    $con = Localconnect();
}
	//Variables to send to javascript to graph output
	$dates=array();
	$numberOfSharesArray=array();
	$profitLossArray=array();
	$gainArray=array();
	$signalsArray=array();
	
if ($_REQUEST['Backtest']) {

    //Get form data
    $Email = $_SESSION['email'];
    //Initial Setup of variables
    $Symbol = $_POST['Symbol'];
    $StartingCapital = $_POST['StartingCapital'];
    $TradingCommission = $_POST['TradingCommission'];
    $StopIndicator = $_POST['StopIndicator'];
    $LongTarget = $_POST['LongTarget'];
    $StopIndicatorInput = $_POST['StopIndicatorInput'];
    $LongTargetInput = $_POST['LongTargetInput'];
    $StartDate = $_POST['StartDate'];
    $EndDate = $_POST['EndDate'];
	$LockSize=$_POST['LockSize']; // Minimum number of shares you can buy and sell

    //this variable is used to calculate the overal profit at the end of the backtesting process
    $BeginningCapital = $StartingCapital;

    //First buy signal
    $Buy1_1 = $_POST['Buy1_1'];
    $Buy1_2 = $_POST['Buy1_2'];
    $Buy1_3 = $_POST['Buy1_3'];
    $BuyInput1_1 = $_POST['BuyInput1_1'];
    $BuyInput1_2 = $_POST['BuyInput1_2'];
    $BuyInput1_3 = $_POST['BuyInput1_3'];

    //First sell signal
    $Sell1_1 = $_POST['Sell1_1'];
    $Sell1_2 = $_POST['Sell1_2'];
    $Sell1_3 = $_POST['Sell1_3'];
    $SellInput1_1 = $_POST['SellInput1_1'];
    $SellInput1_2 = $_POST['SellInput1_2'];
    $SellInput1_3 = $_POST['SellInput1_3'];

    //Helper variables
    //indexer keeps the index of the sma and ema arrays on the same page as the index of the historical data.
    //#Please not indexer value wa changed from 0 to one as sma and ema array was 1 day behind what it was supposed to be.
    $indexer = 1;

    //After some testing I found that in some instances buy and sell transactions where being made on the same day to stop this I am using the 
    //$Transactiondate variable to ensure that transactions cannot be made on the same date.
    $Transactiondate = "";

    //Used at the end of the script when calcualting the total profit/loss of the backtesting process, as if the type is buy then we have to use the variable
    //$initialCostOfShares where as if it is sell we have to use $StartingCapital;
    $lastTransactionType;

    /* check values of form data:
      echo"<Email: $Email<br>";
      echo"<Symbol: $Symbol<br>";
      echo"<TradingCommission: $TradingCommission<br>";
      echo"StopIndicator: $StopIndicator<br>";
      echo"Longtarget: $LongTarget<br>";
      echo"StartDate: $StartDate<br>";
      echo"EndDate: $EndDate<br>";
      echo"First Buy Signal Start:<br>";
      echo"1: $Buy1_1<br>";
      echo"2: $Buy1_2<br>";
      echo"3: $Buy1_3<br>";
      echo"1 Input: $BuyInput1_1<br>";
      echo"2 Input: $BuyInput1_2<br>";
      echo"3 Input: $BuyInput1_3<br>";
      echo"First Sell Signal Start:<br>";
      echo"1: $Sell1_1<br>";
      echo"2: $Sell1_2<br>";
      echo"3: $Sell1_3<br>";
      echo"1 Input: $SellInput1_1<br>";
      echo"2 Input: $SellInput1_2<br>";
      echo"3 Input: $SellInput1_3<br>";
     */
	 
    //setup varibles for backtesting
    $canBuyShares = true;
    $initialCostOfShares = 0;
    $numberOfShares = 0;
	$WinningTrades=0;
	$LosingTrades=0;
	$TotalCommission=0;
	

	
	
	if($Buy1_1=="SMA")
   		$SMAArrayBuy1_1 = SMACalc($StartDate, $EndDate, $BuyInput1_1, $Symbol);
	if($Buy1_3=="SMA")
    	$SMAArrayBuy1_3 = SMACalc($StartDate, $EndDate, $BuyInput1_3, $Symbol);
    if($Sell1_1=="SMA")
		$SMAArraySell_1 = SMACalc($StartDate, $EndDate, $SellInput1_1, $Symbol);
    if($Sell1_3=="SMA")
		$SMAArraySell1_3 = SMACalc($StartDate, $EndDate, $SellInput1_3, $Symbol);
	
	if($Buy1_1=="EMA")
		$EMAArrayBuy1_1 = EMACalc($StartDate, $EndDate, $BuyInput1_1, $Symbol);
    if($Buy1_3=="EMA")
		$EMAArrayBuy1_3 = SMACalc($StartDate, $EndDate, $BuyInput1_3, $Symbol);
    if($Sell1_1=="EMA")
		$EMAArraySell_1 = EMACalc($StartDate, $EndDate, $SellInput1_1, $Symbol);
    if($Sell1_3=="EMA")
		$EMAArraySell1_3 = EMACalc($StartDate, $EndDate, $SellInput1_3, $Symbol);
	
	
	
	//pecl strategies:
	if($Buy1_1=="RSI")
		$RSIArrayBuy1_1 = RSI($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
		
    if($Buy1_3=="RSI")
		$RSIArrayBuy1_3 = RSI($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="RSI")
		$RSIArraySell_1 = RSI($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="RSI")
		$RSIArraySell1_3 = RSI($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);

	
	if($Buy1_1=="SAR")
		$SARArrayBuy1_1 = SAR($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="SAR")
		$SARArrayBuy1_3 = SAR($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="SAR")
		$SARArraySell_1 = SAR($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="SAR")
   		$SARArraySell1_3 = SAR($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);

	if($Buy1_1=="WMA")
		$WMAArrayBuy1_1 = WMA($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="WMA")
		$WMAArrayBuy1_3 = WMA($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="WMA")
		$WMAArraySell_1 = WMA($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="WMA")
   		$WMAArraySell1_3 = WMA($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);	
		
	if($Buy1_1=="BollingerUpper")
		$BollingerUpperArrayBuy1_1 = Bollinger($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);

    if($Buy1_3=="BollingerUpper")
		$BollingerUpperArrayBuy1_3 = Bollinger($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
		
    if($Sell1_1=="BollingerUpper")
		$BollingerUpperArraySell_1 = Bollinger($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
		
    if($Sell1_3=="BollingerUpper")
   		$BollingerUpperArraySell1_3 = Bollinger($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);	


	if($Buy1_1=="BollingerLower")
		$BollingerLowerArrayBuy1_1 = Bollinger($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);

    if($Buy1_3=="BollingerLower")
		$BollingerLowerArrayBuy1_3 = Bollinger($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);

    if($Sell1_1=="BollingerLower")
		$BollingerLowerArraySell_1 = Bollinger($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);

    if($Sell1_3=="BollingerLower")
   		$BollingerLowerArraySell1_3 = Bollinger($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);	
	
	if($Buy1_1=="MacD")
		$MacDArrayBuy1_1 = MacD($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="MacD")
		$MacDArrayBuy1_3 = MacD($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="MacD")
		$MacDArraySell_1 = MacD($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="MacD")
   		$MacDArraySell1_3 = MacD($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);

	if($Buy1_1=="MacDSignal")
		$MacDSignalArrayBuy1_1 = MacD($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="MacDSignal")
		$MacDSignalArrayBuy1_3 = MacD($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="MacDSignal")
		$MacDSignalArraySell_1 = MacD($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="MacDSignal")
   		$MacDSignalArraySell1_3 = MacD($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
		
	if($Buy1_1=="ROC")
		$ROCArrayBuy1_1 = ROC($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="ROC")
		$ROCArrayBuy1_3 = ROC($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="ROC")
		$ROCArraySell_1 = ROC($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="ROC")
   		$ROCArraySell1_3 = ROC($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
		
	if($Buy1_1=="OBV")
		$OBVArrayBuy1_1 = OBV($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="OBV")
		$OBVArrayBuy1_3 = OBV($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="OBV")
		$OBVArraySell_1 = OBV($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="OBV")
   		$OBVArraySell1_3 = OBV($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
		
	if($Buy1_1=="WilliamR")
		$WilliamRArrayBuy1_1 = WilliamR($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="WilliamR")
		$WilliamRArrayBuy1_3 = WilliamR($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="WilliamR")
		$WilliamRArraySell_1 = WilliamR($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="WilliamR")
   		$WilliamRArraySell1_3 = WilliamR($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);

	if($Buy1_1=="MTM")
		$MTMArrayBuy1_1 = MTM($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="MTM")
		$MTMArrayBuy1_3 = MTM($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="MTM")
		$MTMArraySell_1 = MTM($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="MTM")
   		$MTMArraySell1_3 = MTM($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
		
	if($Buy1_1=="fastSTCk")
		$fastSTCkArrayBuy1_1 = FastSTC($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="fastSTCk")
		$fastSTCkArrayBuy1_3 = FastSTC($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="fastSTCk")
		$fastSTCkArraySell_1 = FastSTC($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="fastSTCk")
   		$fastSTCkArraySell1_3 = FastSTC($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);

	if($Buy1_1=="fastSTCd")
		$fastSTCdArrayBuy1_1 = FastSTC($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="fastSTCd")
		$fastSTCdArrayBuy1_3 = FastSTC($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="fastSTCd")
		$fastSTCdArraySell_1 = FastSTC($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="fastSTCd")
   		$fastSTCdArraySell1_3 = FastSTC($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
		
	if($Buy1_1=="DMIplus")
		$DMIplusArrayBuy1_1 = DMI($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
		
    if($Buy1_3=="DMIplus")
		$DMIplusArrayBuy1_3 = DMI($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="DMIplus")
		$DMIplusArraySell_1 = DMI($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="DMIplus")
   		$DMIplusArraySell1_3 = DMI($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
	
	if($Buy1_1=="DMIminus")
		$DMIminusArrayBuy1_1 = DMI($StartDate, $EndDate, $BuyInput1_1, $Symbol,$con);
    if($Buy1_3=="DMIminus")
		$DMIminusArrayBuy1_3 = DMI($StartDate, $EndDate, $BuyInput1_3, $Symbol,$con);
    if($Sell1_1=="DMIminus")
		$DMIminusArraySell_1 = DMI($StartDate, $EndDate, $SellInput1_1, $Symbol,$con);
    if($Sell1_3=="DMIminus")
   		$DMIminusArraySell1_3 = DMI($StartDate, $EndDate, $SellInput1_3, $Symbol,$con);
	
    /* TESTING:
      $SMATestBuy1=DateTestSMA($StartDate, $EndDate, $BuyInput1_1, $Symbol);
      $SMATestBuy3=DateTestSMA($StartDate, $EndDate, $BuyInput1_3, $Symbol);
      $SMATestSell1=DateTestSMA($StartDate, $EndDate, $SellInput1_1, $Symbol);
      $SMATestSell3=DateTestSMA($StartDate, $EndDate, $SellInput1_3, $Symbol);
     */
	 

		//$EMATestBuy1 = DateTestEMA($StartDate, $EndDate, $BuyInput1_3, $Symbol);
		//$EMATestBuy3 = DateTestEMA($StartDate, $EndDate, $BuyInput1_3, $Symbol);
		
	

    //obtain historical data in the range of the start date and end date from the database
	

	
    $historicalData = mysqli_query($con, "SELECT * FROM `shares` WHERE  `Symbol` =  '$Symbol' AND  `date` BETWEEN  '$StartDate' AND  '$EndDate'");

    //make a table to display the data in:
	
    echo "<table border='1' cellspacing='5' cellpadding='2'>";
    echo"<tr>";
    echo"<td><strong>Date</strong></td>";
    echo"<td><strong>Signal</strong></td>";
    echo"<td><strong>Stock</strong></td>";
    echo"<td><strong>Price</strong></td>";
    echo"<td><strong>Number</strong></td>";
    echo"<td><strong>Value</strong></td>";
    echo"<td><strong>Profit/Loss</strong></td>";
    echo"<tr>";

    while ($row = mysqli_fetch_array($historicalData)) {

        $currentPriceOfShares = $row['Close'];
        $thedate = $row['Date'];

		
       /* TESTING:
          echo"DATE OF HISTORICAL DATA: $thedate <br>";
        */
		
	
        //check if buy signal is met:
        if ($canBuyShares == true && $Transactiondate != $thedate) {
			
            switch ($Buy1_1) {
                case "SMA":
                    //Run SMA Algorithm
                    $Buy1 = $SMAArrayBuy1_1[$indexer];
                    /* TESTING:
                      $Buy1test=$SMATestBuy1[$indexer];
                      echo"BUY1 TEST DATE: $Buy1test<br>";
                     */
                    break;
                case "EMA":
                    $Buy1 = $EMAArrayBuy1_1[$indexer];
					 /* TESTING:
                      $Buy1test2=$EMATestBuy1[$indexer];
                      echo"BUY1 TEST DATE: $Buy1test2<br>";
                     */
                    break;
                case "ClosingPrice":
                    $Buy1 = $row['Close'];
                    break;
                case "OpeningPrice":
                    $Buy1 = $row['Open'];
                    break;
                case "Highest":
                    $Buy1 = $row['High'];
                    break;
                case "Lowest":
                    $Buy1 = $row['Low'];
                    break;
                case "Volume":
                    $Buy1 = $row['Volume'];
                    break;
				case "RSI":
					$Buy1= $RSIArrayBuy1_1[$indexer-1];
					break;
				case "Value":
					$Buy1= $BuyInput1_1;
					break;
				case "SAR":
					$Buy1= $SARArrayBuy1_1[0][$indexer];
					break;
				case "WMA":
					$Buy1= $WMAArrayBuy1_1[$indexer-1];
					break;
				case "BollingerUpper":
					$Buy1= $BollingerUpperArrayBuy1_1[0][$indexer-1];
					break;
				case "BollingerLower":
					$Buy1= $BollingerLowerArrayBuy1_1[2][$indexer-1];
					break;
				case "MacD":
					$Buy1= $MacDArrayBuy1_1[0][$indexer-1];
					break;
				case "MacDSignal":
					$Buy1= $MacDSignalArrayBuy1_1[1][$indexer-1];
					break;
				case "ROC":
					$Buy1= $ROCArrayBuy1_1[$indexer-1];
					break;
				case "OBV":
					$Buy1= $OBVArrayBuy1_1[0][$indexer-1];
					break;
				case "WilliamR":
					$Buy1= $WilliamRArrayBuy1_1[$indexer-1];
					echo $WilliamRArrayBuy1_1[$indexer-1];
					echo"<br>";
					break;
				case "MTM":
					$Buy1= $MTMArrayBuy1_1[$indexer-1];
					echo $MTMArrayBuy1_1[$indexer-1];
					echo"<br>";
					break;
				case "fastSTCk":
					$Buy1= $fastSTCkArrayBuy1_1[0][$indexer-1];
					break;
				case "fastSTCd":
					$Buy1= $fastSTCdArrayBuy1_1[1][$indexer-1];
					break;
				case "DMIplus":
					$Buy1= $DMIplusArrayBuy1_1[0][$indexer-1];
					break;
				case "DMIminus":
					$Buy1= $DMIminusArrayBuy1_1[1][$indexer-1];
					break;
					
            }
            //check $Buy1_3
            switch ($Buy1_3) {
                case "SMA":
                    //Run SMA Algorithm
                    /* TESTING:
                      $Buy3test=$SMATestBuy3[$indexer];
                      echo"BUY3 TEST DATE: $Buy3test<br>";
                     */
                    $Buy3 = $SMAArrayBuy1_3[$indexer];
                    break;
                case "EMA":
                    $Buy3 = $EMAArrayBuy1_3[$indexer];
					 /* TESTING:
					$Buy3test2=$EMATestBuy3[$indexer];
                      echo"BUY3 TEST DATE: $Buy3test2<br>";
					  */
                    break;
                case "ClosingPrice":
                    $Buy3 = $row['Close'];
                    break;
                case "OpeningPrice":
                    $Buy3 = $row['Open'];
                    break;
                case "Highest":
                    $Buy3 = $row['High'];
                    break;
                case "Lowest":
                    $Buy3 = $row['Low'];
                    break;
                case "Volume":
                    $Buy3 = $row['Volume'];
                    break;
				case "RSI":
					$Buy3= $RSIArrayBuy1_3[$indexer-1];
					break;
				case "Value":
					$Buy3= $BuyInput1_3;
					break;
				case "SAR":
					$Buy3= $SARArrayBuy1_3[0][$indexer];
					break;
				case "WMA":
					$Buy1= $WMAArrayBuy1_3[$indexer-1];
					break;
				case "BollingerUpper":
					$Buy3= $BollingerUpperArrayBuy1_3[0][$indexer-1];
					break;
				case "BollingerLower":
					$Buy3= $BollingerLowerArrayBuy1_3[2][$indexer-1];
					break;
				case "MacD":
					$Buy3= $MacDArrayBuy1_3[0][$indexer-1];
					break;
				case "MacDSignal":
					$Buy3= $MacDSignalArrayBuy1_3[1][$indexer-1];
					break;
				case "ROC":
					$Buy3= $ROCArrayBuy1_3[$indexer-1];
					break;
				case "OBV":
					$Buy3= $OBVArrayBuy1_3[0][$indexer-1];
					break;
				case "WilliamR":
					$Buy3= $WilliamRArrayBuy1_3[$indexer-1];
					break;
				case "MTM":
					$Buy3= $MTMArrayBuy1_3[$indexer-1];
					break;
				case "fastSTCk":
					$Buy3= $fastSTCkArrayBuy1_3[0][$indexer-1];
					break;
				case "fastSTCd":
					$Buy3= $fastSTCdArrayBuy1_3[1][$indexer-1];
					break;
				case "DMIplus":
					$Buy3= $DMIplusArrayBuy1_3[0][$indexer-1];
					break;
				case "DMIminus":
					$Buy3= $DMIminusArrayBuy1_3[1][$indexer-1];
					break;
					
					
            }
            //Test buy signal algorithm here:

            switch ($Buy1_2) {
                case "Above":

                    //Buy1_1>Buy1_3
                    if ($Buy1 > $Buy3) {
						$numberOfShares=0;
                        //buy as many shares as you can
                        $StartingCapital = $StartingCapital - $TradingCommission;
                        for ($i = $StartingCapital - $TradingCommission; $i > 0; $i-=$currentPriceOfShares) {
                            $numberOfShares+=1;
                        }
						//check if the lock size is met
						if($numberOfShares>=$LockSize){
						
                        //calculate the cost
                        $initialCostOfShares = $numberOfShares * $currentPriceOfShares + $TradingCommission;
                        //double check that the cost is not more than starting capital
                        if ($StartingCapital - $TradingCommission < $initialCostOfShares) {
                            $initialCostOfShares-=$currentPriceOfShares;
                        }
                        //remove cost of shares from starting capital
                        $StartingCapital-=$initialCostOfShares;
                        $canBuyShares = false;

                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Buy";
                        //output here

                        TableOutput($thedate, "Buy", $Symbol, $currentPriceOfShares, $numberOfShares, $initialCostOfShares, 0);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,$profitLoss);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Buy");
						}
						
                    }
                    break;
                case "Below":
                    //Buy1_1<Buy1_3

                    if ($Buy1 < $Buy3) {
						$numberOfShares=0;
                        //buy as many shares as you can
                        for ($i = $StartingCapital - $TradingCommission; $i >= 0; $i-=$currentPriceOfShares) {
                            $numberOfShares+=1;
                        }
						
						
						//check if the lock size is met
						if($numberOfShares>=$LockSize){
                        //calculate the cost
                        $initialCostOfShares = $numberOfShares * $currentPriceOfShares + $TradingCommission;
                        //double check that the cost is not more than starting capital
                        if ($StartingCapital - $TradingCommission < $initialCostOfShares) {
                            $initialCostOfShares-=$currentPriceOfShares;
                        }
                        //remove cost of shares from starting capital
                        $StartingCapital-=$initialCostOfShares;
                        $canBuyShares = false;
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Buy";

                        //output here

                        TableOutput($thedate, "Buy", $Symbol, $currentPriceOfShares, $numberOfShares, $initialCostOfShares, 0);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,0);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Buy");
                    }
					}
                    break;
                case "AtLeast%Above%":
                    $percentage = CalculatePercentage($Buy1, $Buy3);
					
                    if ($percentage > $BuyInput1_2) {
						$numberOfShares=0;
                        for ($i = $StartingCapital - $TradingCommission; $i >= 0; $i-=$currentPriceOfShares) {
                            $numberOfShares+=1;
                        }
						
						
						//check if the lock size is met
						if($numberOfShares>=$LockSize){
                        //calculate the cost
                        $initialCostOfShares = $numberOfShares * $currentPriceOfShares + $TradingCommission;
                        //double check that the cost is not more than starting capital
                        if ($StartingCapital - $TradingCommission < $initialCostOfShares) {
                            $initialCostOfShares-=$currentPriceOfShares;
                        }
                        //remove cost of shares from starting capital
                        $StartingCapital-=$initialCostOfShares;
                        $canBuyShares = false;
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Buy";

                        TableOutput($thedate, "Buy", $Symbol, $currentPriceOfShares, $numberOfShares, $initialCostOfShares, 0);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,0);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Buy");
                    }
					}
                    break;
                case "AtLeast%Below%":
					
                    $percentage = CalculatePercentage($Buy1, $Buy3);
                    if ($percentage < -$BuyInput1_2) {
						$numberOfShares=0;
                        for ($i = $StartingCapital - $TradingCommission; $i >= 0; $i-=$currentPriceOfShares) {
                            $numberOfShares+=1;
                        }
						
						//check if the lock size is met
						if($numberOfShares>=$LockSize){
							
                        //calculate the cost
                        $initialCostOfShares = $numberOfShares * $currentPriceOfShares + $TradingCommission;
                        //double check that the cost is not more than starting capital
                        if ($StartingCapital - $TradingCommission < $initialCostOfShares) {
                            $initialCostOfShares-=$currentPriceOfShares;
                        }
                        //remove cost of shares from starting capital
                        $StartingCapital-=$initialCostOfShares;
                        $canBuyShares = false;
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Buy";
                        TableOutput($thedate, "Buy", $Symbol, $currentPriceOfShares, $numberOfShares, $initialCostOfShares, 0);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,0);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Buy");
                    }
					}
                    break;
            }
        }

        //check if we can sell
        if ($canBuyShares == false && $Transactiondate != $thedate) {
            //check if any sell signal is met

            switch ($Sell1_1) {
                case "SMA":
                    //Run SMA Algorithm
                    $Sell1 = $SMAArraySell_1[$indexer];
                    /* TESTING:
                      $Sell1test=$SMATestSell1[$indexer];
                      echo"Sell1 TEST DATE: $Sell1test<br>";
                     */
                    break;
                case "EMA":
                    $Sell1 = $EMAArraySell_1 [$indexer];
                    break;
                case "ClosingPrice":
                    $Sell1 = $row['Close'];
                    break;
                case "OpeningPrice":
                    $Sell1 = $row['Open'];
                    break;
                case "Highest":
                    $Sell1 = $row['High'];
                    break;
                case "Lowest":
                    $Sell1 = $row['Low'];
                    break;
                case "Volume":
                    $Sell1 = $row['Volume'];
                    break;
				case "RSI":
					$Sell1 = $RSIArraySell_1[$indexer-1];
					break;
				case "Value":
					$Sell1 = $SellInput1_1;
					break;
				case "SAR":
					$Sell1 = $SARArraySell_1[0][$indexer];
					break;
				case "WMA":
					$Sell1 = $WMAArraySell_1[$indexer-1];
					break;
				case "BollingerUpper":
					$Sell1 = $BollingerUpperArraySell_1[0][$indexer-1];
					break;
				case "BollingerLower":
					$Sell1 = $BollingerLowerArraySell_1[2][$indexer-1];
					break;
				case "MacD":
					$Sell1 = $MacDArraySell_1[0][$indexer-1];
					break;
				case "MacDSignal":
					$Sell1 = $MacDSignalArraySell_1[1][$indexer-1];
					break;
				case "ROC":
					$Sell1 = $ROCArraySell_1[$indexer-1];
					break;
				case "OBV":
					$Sell1 = $OBVArraySell_1[0][$indexer-1];
					break;
				case "WilliamR":
					$Sell1 = $WilliamRArraySell_1[$indexer-1];
					break;
				case "MTM":
					$Sell1 = $MTMArraySell_1[$indexer-1];
					break;
				case "fastSTCk":
					$Sell1 = $fastSTCkArraySell_1[0][$indexer-1];
					break;
				case "fastSTCd":
					$Sell1 = $fastSTCdArraySell_1[1][$indexer-1];
					break;
				case "DMIplus":
					$Sell1 = $DMIplusArraySell_1[0][$indexer-1];
					break;
				case "DMIminus":
					$Sell1 = $DMIminusArraySell_1[1][$indexer-1];
					break;
            }
			
			//check $Buy1_3
			switch ($Sell1_3) {
				case "SMA":
					//Run SMA Algorithm

					$Sell3 = $SMAArraySell1_3[$indexer];
					/* TESTING:
					  $Sell3test=$SMATestSell3[$indexer];
					  echo"Sell3 TEST DATE: $Sell3test<br>";
					 */

					break;
				case "EMA":
					$Sell3 = $EMAArraySell1_3 [$indexer];
					break;
				 case "ClosingPrice":
                    $Sell3 = $row['Close'];
                    break;
                case "OpeningPrice":
                    $Sell3 = $row['Open'];
                    break;
                case "Highest":
                    $Sell3 = $row['High'];
                    break;
                case "Lowest":
                    $Sell3 = $row['Low'];
                    break;
                case "Volume":
                    $Sell3 = $row['Volume'];
                    break;
				case "RSI":
					$Sell3 = $RSIArraySell1_3[$indexer-1];
					break;
				case "Value":
					$Sell3 = $SellInput1_3;
					break;
				case "SAR":
					$Sell3 = $SARArraySell1_3[0][$indexer];
					break;
				case "WMA":
					$Sell3 = $WMAArraySell1_3[$indexer-1];
					break;
				case "BollingerUpper":
					$Sell3 = $BollingerUpperArraySell1_3[0][$indexer-1];
					break;
				case "BollingerLower":
					$Sell3 = $BollingerLowerArraySell1_3[2][$indexer-1];
					break;
				case "MacD":
					$Sell3 = $MacDArraySell1_3[0][$indexer-1];
					break;
				case "MacDSignal":
					$Sell3 = $MacDSignalArraySell1_3[1][$indexer-1];
					break;
				case "ROC":
					$Sell3 = $ROCArraySell1_3[$indexer-1];
					break;
				case "OBV":
					$Sell3 = $OBVArraySell1_3[0][$indexer-1];
					break;
				case "WilliamR":
					$Sell3 = $WilliamRArraySell1_3[$indexer-1];
					break;
				case "MTM":
					$Sell3 = $MTMArraySell1_3[$indexer-1];
					break;
				case "fastSTCk":
					$Sell3 = $fastSTCkArraySell1_3[0][$indexer-1];
					break;
				case "fastSTCd":
					$Sell3 = $fastSTCdArraySell1_3[1][$indexer-1];
					break;
				case "DMIplus":
					$Sell3 = $DMIplusArraySell1_3[0][$indexer-1];
					break;
				case "DMIminus":
					$Sell3 = $DMIminusArraySell1_3[1][$indexer-1];
					break;
					
	
			}
            //Test sell signal algorithm here:

            switch ($Sell1_2) {
                case "Above":

                    //Sell1_1>Sell1_3
                    if ($Sell1 > $Sell3) {
                        //Calculate value of shares
                        $Value = ($numberOfShares * $currentPriceOfShares);
                        //sell the shares
                        $StartingCapital+=$Value - $TradingCommission;
                        $profitLoss = ($Value - $TradingCommission) - $initialCostOfShares;
						
						//check if the sell is a winning trade
							if(IsWinning($profitLoss)){
								$WinningTrades+=1;	
							}else{$LosingTrades+=1;}
						
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Sell";
                        TableOutput($thedate, "Sell", $Symbol, $currentPriceOfShares, $numberOfShares, $Value, $profitLoss);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,$profitLoss);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Sell");
                        $numberOfShares = 0;
                        $canBuyShares = true;
                    }
                    break;
                case "Below":
                    //Sell1_1<Sell1_3

                    if ($Sell1 < $Sell3) {

                        //Calculate value of shares
                        $Value = ($numberOfShares * $currentPriceOfShares);
                        //sell the shares
                        $StartingCapital+=$Value - $TradingCommission;


                        $profitLoss = ($Value - $TradingCommission) - $initialCostOfShares;
						
						//check if the sell is a winning trade
							if(IsWinning($profitLoss)){
								$WinningTrades+=1;	
							}else{$LosingTrades+=1;}		
									
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Sell";
                        TableOutput($thedate, "Sell", $Symbol, $currentPriceOfShares, $numberOfShares, $Value, $profitLoss);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,$profitLoss);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Sell");
                        $numberOfShares = 0;
                        $canBuyShares = true;
                    }
                    break;
                case "AtLeast%Above%":
                    $percentage = CalculatePercentage($Sell1, $Sell3);

                    if ($percentage > $SellInput1_2) {

                        //Calculate value of shares
                        $Value = ($numberOfShares * $currentPriceOfShares);
                        //sell the shares

                        $StartingCapital+=$Value - $TradingCommission;

                        $profitLoss = ($Value - $TradingCommission) - $initialCostOfShares;
						
						//check if the sell is a winning trade
							if(IsWinning($profitLoss)){
								$WinningTrades+=1;	
							}else{$LosingTrades+=1;}
						
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Sell";
                        TableOutput($thedate, "Sell", $Symbol, $currentPriceOfShares, $numberOfShares, $Value, $profitLoss);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,$profitLoss);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Sell");
                        $numberOfShares = 0;
                        $canBuyShares = true;
                    }
                    break;
                case "AtLeast%Below%":
                    $percentage = CalculatePercentage($Sell1, $Sell3);

                    if ($percentage < -$SellInput1_2) {

                        //Calculate value of shares
                        $Value = ($numberOfShares * $currentPriceOfShares);
                        //sell the shares
                        $StartingCapital+=$Value - $TradingCommission;


                        $profitLoss = ($Value - $TradingCommission) - $initialCostOfShares;
						
						//check if the sell is a winning trade
							if(IsWinning($profitLoss)){
								$WinningTrades+=1;	
							}else{$LosingTrades+=1;}
						
                        //stop multiple transactions on the same day:
                        $Transactiondate = $thedate;
                        $lastTransactionType = "Sell";

                        TableOutput($thedate, "Sell", $Symbol, $currentPriceOfShares, $numberOfShares, $Value, $profitLoss);
						//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
						array_push($gainArray,$profitLoss);
						array_push($profitLossArray,$Value);
						array_push($numberOfSharesArray,$numberOfShares);	
						array_push($dates,$thedate);
						array_push($signalsArray,"Sell");
                        $numberOfShares = 0;
                        $canBuyShares = true;
                    }
                    break;
            }
            //re check if we can sell shares- if we dont  stop long switch will fire
            if ($canBuyShares == false && $Transactiondate != $thedate) {
                //test risk level stop 
                switch ($StopIndicator) {
                    case "TrailingStop%":
                        //to be implemented later
                        break;
                    case "Stop%":
                        //calculate the % profit
                        $profit = CalculateProfitPercentage($numberOfShares, $currentPriceOfShares, $TradingCommission, $initialCostOfShares);
                        //check if the profit is at a loss greater than the risk acceptance level.
                        if ($profit <= -$StopIndicatorInput) {
                            //sell the shares
                            //Calculate value of shares
                            $Value = ($numberOfShares * $currentPriceOfShares);
                            //sell the shares
                            $StartingCapital+=$Value - $TradingCommission;

                            $profitLoss = ($Value - $TradingCommission) - $initialCostOfShares;
						
							//check if the sell is a winning trade
							if(IsWinning($profitLoss)){
								$WinningTrades+=1;	
							}else{$LosingTrades+=1;}
							
                            //stop multiple transactions on the same day:
                            $Transactiondate = $thedate;
                            $lastTransactionType = "Sell";
                            TableOutput($thedate, "Stop Long", $Symbol, $currentPriceOfShares, $numberOfShares, $Value, $profitLoss);
							//add all the things to the arrays to send to the javascript graphs
							$Value= $currentPriceOfShares*$numberOfShares;
							array_push($gainArray,$profitLoss);
							array_push($profitLossArray,$Value);
							array_push($numberOfSharesArray,$numberOfShares);	
							array_push($dates,$thedate);
							array_push($signalsArray,"Stop Long");
                            $numberOfShares = 0;
                            $canBuyShares = true;
                        }
                        break;
                }

                //test profit level stop
                switch ($LongTarget) {
                    case "UseReturnTarget%":
                        $profit = CalculateProfitPercentage($numberOfShares, $currentPriceOfShares, $TradingCommission, $initialCostOfShares);
                        if ($profit >= $LongTargetInput) {
                            //Calculate value of shares
                            $Value = ($numberOfShares * $currentPriceOfShares);
                            //sell the shares

                            $StartingCapital+=$Value - $TradingCommission;
                            $profitLoss = ($Value - $TradingCommission) - $initialCostOfShares;

							//check if the sell is a winning trade
							if(IsWinning($profitLoss)){
								$WinningTrades+=1;	
							}else{$LosingTrades+=1;}
							
                            //stop multiple transactions on the same day:
                            $Transactiondate = $thedate;
                            $lastTransactionType = "Sell";
                            TableOutput($thedate, "Long Target", $Symbol, $currentPriceOfShares, $numberOfShares, $Value, $profitLoss);
							//add all the things to the arrays to send to the javascript graphs
						$Value= $currentPriceOfShares*$numberOfShares;
							array_push($gainArray,$profitLoss);
							array_push($profitLossArray,$Value);
							array_push($numberOfSharesArray,$numberOfShares);	
							array_push($dates,$thedate);
							array_push($signalsArray,"Long Target");
                            $numberOfShares = 0;
                            $canBuyShares = true;
                        }
                        break;
                    case "Don't Use Target":
                        //do nothing at the moment.
                        break;
                }
            }
        }
        //push the Sma/Ema arrays along so that they stay on track with the historical data
        $indexer+=1;
    }

    //end table formating
    echo "<table>";
    $endValue = 0;
	if(isset($lastTransactionType)){
		
    if ($lastTransactionType == "Buy") {
        $endValue = $initialCostOfShares;
    } else {
        $endValue = $StartingCapital;
    }
	}
    $totalreturn = $endValue - $BeginningCapital;
    echo"<table border='1' cellspacing='5' cellpadding='2'>";
    echo"<tr>";
    echo"<td>Start value</td>";
    echo"<td>End value</td>";
    echo"<td>Total return</td>";
	echo"<td>Winning Trades</td>";
    echo"<td>Losing Trades</td>";
	echo"<td>Winning %</td>";
	echo"<td>Min Number of Shares </td>";
    echo"<tr>";
    echo"<tr>";
    echo"<td>$$BeginningCapital</td>";
    echo"<td>$$endValue</td>";
    echo"<td>$$totalreturn</td>";
	echo"<td>$WinningTrades</td>";
	echo"<td>$LosingTrades</td>";
	//prevent any divisions by 0
	if($WinningTrades!=0|$LosingTrades!=0){
	echo"<td>".$WinningTrades/($WinningTrades+$LosingTrades)*100 ."%</td>";
	}else{
		echo"<td>Something whent wrong...</td>";	
	}
	echo"<td>$LockSize</td>";
    echo"<tr>";
    echo"<table>";
} else {

    echo"sorry something whent wrong!";
}
//refresh page with the data for the javascripts to make charts




function CalculateProfitPercentage($numberOfShares, $currentPriceOfShares, $TradingCommission, $initialCostOfShares) {
    //set up variables
    $firstCost = $initialCostOfShares;
    $currentPrice = ($numberOfShares * $currentPriceOfShares) + $TradingCommission;
    //calculation
    $profit = $firstCost / $currentPrice;
    $profit = 1 - $profit;
    $profit = $profit * 100;
	
   //return current profit%
    return $profit;
	
}

function CalculatePercentage($Buy1, $Buy3) {

    //calculation
    $percentage = $Buy1 / $Buy3;

    $percentage = 1 - $percentage;
    $percentage = $percentage * 100;

    //return percentage
    return $percentage;
}

function IsWinning($profitLoss){
	if($profitLoss>0){
		return true;	
	}else{
		return false;
	}
		
}



function TableOutput($date, $signal, $symbol, $currentPrice, $numberOfShares, $value, $profitLoss) {
    $red = "#FF3300";
    $green = "#66CC33";
    $nothing = "#FFFFFF";
    $color = "";
    if ($profitLoss == 0) {
        $color = $nothing;
    }
    if ($profitLoss > 0) {
        $color = $green;
    }
    if ($profitLoss < 0) {
        $color = $red;
    }

	
    echo"<tr bgcolor='$color'>";
    echo"<td>$date</td>";
    echo"<td>$signal</td>";
    echo"<td>$symbol</td>";
    echo"<td>$currentPrice</td>";
    echo"<td>$numberOfShares</td>";
    echo"<td>$value</td>";
    echo"<td>$profitLoss</td>";
    echo"<tr>";
	
}
echo $indexer;

?>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['annotationchart']}]}"></script>
    <script type='text/javascript'>
      google.load('visualization', '1', {'packages':['annotationchart']});
      google.setOnLoadCallback(profitLossDrawChart);
	  google.setOnLoadCallback(VolumeDrawChart);
	  
	  	var profitLoss=<?php echo json_encode($profitLossArray); ?>;
		var gain=<?php echo json_encode($gainArray); ?>;
		var time=<?php echo json_encode($dates); ?>;
		var signal=<?php echo json_encode($signalsArray); ?>;
	  
      function profitLossDrawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', <?php echo json_encode($Symbol); ?>);
        data.addColumn('string', 'Signals');
		data.addColumn('string', 'Profit');
		
				
        //data.addColumn('number', 'second strategy profit');
		//data.addColumn('string', 'second strategy signal');

		/* 
        data.addRows([
         [new Date(2314, 2, 15), 0, "buy" ,0, undefined],                                  
          [new Date(2314, 2, 16), -400, 'stop long',0, undefined],
          [new Date(2314, 2, 17), -400, 'buy',0, 'buy'],
          [new Date(2314, 2, 18), 37.50, 'sell',1900, 'long target'],
		  [new Date(2314, 2, 19), 37.50, 'buy',1900, 'buy'],
		  [new Date(2314, 2, 20), 37.50, undefined,1900, undefined],
		  [new Date(2314, 2, 22), 37.50, undefined,1900, undefined],  
		  [new Date(2314, 2, 24), 890, 'long target',2244, 'sell'],
		  [new Date(2314, 2, 28), 890, 'buy',2244, undefined]
		
		
        ]);
		*/
	  
	//for the length of the Symbol data array
		
		console.log("time: "+time.length);	
  		for(i = 0; i < time.length; i++){
	  
	  //add row based on count of symbols
			var row=[];
	
			var date= time[i].split("-");
			row.push(new Date(date[0], date[1],date[2]));
			console.log("Date test--2314, 2, 15)");
			console.log(date[0], date[1],date[2]);
	
			row.push(Number(profitLoss[i]));
			row.push(signal[i]);
			row.push("Profit: "+gain[i]);
			data.addRow(row);
		}

        var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

        var options = {
		  displayAnnotations: true,
          title: 'Profit Loss',
          hAxis: {title: 'dates',  titleTextStyle: {color: '#333'}},
          vAxis: {title: 'profit', minValue: 0}
        };

        chart.draw(data, options);
      }
	 
	  
	  
	  

	   
function VolumeDrawChart() {//Volume
	

	  
  var time = <?php echo json_encode($dates); ?>;
  var volumeData=<?php echo json_encode($numberOfSharesArray); ?>;
 
  console.log("dates");
  console.log(time);
  console.log("volumeData");
  console.log(volumeData);

  var data = new google.visualization.DataTable();
  data.addColumn('string', 'days');
  
  	//add column for each symbol
	
	

	
		data.addColumn('number',<?php echo json_encode($Symbol); ?>);	
		
	
	  
	//for the length of the Symbol data array
		
	console.log("time: "+time.length);	
  for(i = 0; i < time.length; i++){
	  
	  //add row based on count of symbols
	var row=[];
	
	
	row.push(time[i]);
	
	
	row.push(Number(volumeData[i]));
	data.addRow(row);
	}
	
    

	
  		
		var Max=Math.max.apply(Math, volumeData);
		console.log(Max);
		var options = {
          title: 'Number of Shares',
          hAxis: {title: 'Day',  titleTextStyle: {color: '#333'}},
          vAxis: {title: 'No. of Shares'},
		     viewWindow: {
        		max:Max,
        		min:0
   			 }
        };

        var chart = new google.visualization.AreaChart(document.getElementById('volumeChart_div'));
        chart.draw(data, options);
      
}
    </script>
      </head>

  <body>
  	<h3> Profit and Loss</h3>
    <div id='chart_div' style='width: 1000px; height: 600px;'></div>
    <div id='volumeChart_div' style='width: 1000px; height: 300px;'></div>
  </body>
</html>
<?php






/*

  Obtain historical data in the range of the start date and end date from the database
  while(rows){
  $haveBroughtShares=false
  $InitialCostOfShares
  $currentPriceOfShares=$row['Close'];
  $numberOfShares
  $profitLoss

  $resultCash
  check if buy signal is met

  if yes and $haveBroughtShares=false
  buy as many shares as you can
  for(i=$resultCash; i>=0 i--$currentPriceOfShares){
  $numberOfShares+=1;
  }
  $initialCostOfShares=$numberOfShares*currentPriceOfShares;
  $haveBroughtShares=true

  echo output.


  check if $HaveBroughtShares=true
  check if sell signal is met
  if yes
  sell shares->$resultCash;

  echo output.

  check if StopIndicator signal is met if sell signal was not met
  //sell because lossing too much eg. 10%loss<-Use CalculateProfit method to check
  if yes
  sell shares->$resultCash;

  echo output

  check if Longtarget signal is met if sell signal was not met
  //sell because target earning reached eg.10%profit<-Use CalculateProfit method to check
  if yes
  sell shares->$resultCash;

  echo output
  }

  function CalculateProfit(numberOfShares, currentPriceOfShares, costOfCommission, InitialCostOfShares{

  //return current profit in percentage form

  }

  After the above is working perfectly we can work on making the script have multiple buy and sell signals.

  Inorder to make the stock backtesting script to test than 1 buy signal and more than 1 sell signal we will need to:

  -Implement a dynamically changing front end to provide the user with more forms in which they can fill out.
  -The user inputs how many buy signals and how many sell signals he wants.
  -the page is refreshed with the correct number of buy signals and sell signals
  -In addition the form contents id's and names need to be unique and follow the same naming convention

  -Inorder to keep track of all the buy and sell signals we will have to use an array of arrays, one for the sell signals and one for the buy signals.
  eg. javish code:
  public int numberOfBuy;
  public int numberOfsell;
  public ArrayList<ArrayList> buyList = new ArrayList<ArrayList>();

  //Add new ArrayLists into the buyList
  for(i=0;i<numberOfBuy;i++){
  buyList.add(new ArrayList<Integer>());
  }
  //This will leave use with an array of arrays

  //Now we will need to populate the empty arrays inside the buyList with buySignals

  //the naming convention is Signal 1: buy1_1, buy1_2 etc etc
  //the naming convention is Signal 2: buy2_1, buy2_2 etc etc
  for(i=1;i<numberOfBuy;i++){
  //their are three signal elements in a signal so...
  for(j=1;j<3;j++){
  String SignalElement=$_POST["buy".i."_".j.""];
  buyList.get(i-1).add(SignalElement);
  }

  }
  //This has populated the previously empty arrays now we need to itterate through the buy array when we go to do the backtesting.
  //We will also need to store which of the buy signals used to buy the shares
  -However the problem to ask Carrie is. How does she want us to handle the buying logic. What do we do if 2 of the users buy signals are met on the same date?

 */
?>
